package com.huawei.bigdata.flink.examples.utils;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;

public class ImagerToBase {
    static BASE64Encoder encode = new BASE64Encoder();
    static BASE64Decoder ecoder = new BASE64Decoder();
    public static void main(String[] args) throws Exception{


        BufferedReader bufferedReader = new BufferedReader(new FileReader(new File("/opt/fwx/Voucher/detail.csv")));
        String[] fieldsArr = null;
        String line = null;
        while ((line=bufferedReader.readLine())!=null){
            fieldsArr=line.split(",");
            System.out.println(fieldsArr[3]);
            String t = line+","+getImageBinary(fieldsArr[3]);
            System.out.println(t);
            System.out.println(t.getBytes("UTF-8").toString());
        }
//        System.out.println(getImageBinary());
//        base64StringToImage(getImageBinary());
    }

    private static void base64StringToImage(String base64String) {

        try {
            byte[] bytes1 = ecoder.decodeBuffer(base64String);

            ByteArrayInputStream bais = new ByteArrayInputStream(bytes1);
            BufferedImage bi1 = ImageIO.read(bais);
            File w2 = new File("D:\\ceshi1.jpg");// 可以是jpg,png,gif格式
            ImageIO.write(bi1,"jpg", w2);// 不管输出什么格式图片，此处不需改动
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static String getImageBinary(String str){
        File f = new File("/opt/fwx/Voucher/picture/"+str);
        BufferedImage bi;
        try {
            bi = ImageIO.read(f);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(bi,"jpg", baos);  //经测试转换的图片是格式这里就什么格式，否则会失真
            byte[] bytes = baos.toByteArray();
            return encode.encodeBuffer(bytes).trim();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;

    }

}

